package all.com.jinyongqunxiax.modules;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.jacksonandroidnetworking.JacksonParserFactory;
import com.randy.fundation.ImageUitls;
import com.randy.fundation.JSONUtility;
import com.randy.fundation.Logger;
import com.sak.ultilviewlib.UltimateRefreshView;
import com.sak.ultilviewlib.interfaces.OnFooterRefreshListener;
import com.theartofdev.edmodo.cropper.CropImage;
import com.yalantis.ucrop.UCrop;

import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;

import org.apache.commons.io.FilenameUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import all.com.jinyongqunxiax.R;
import all.com.jinyongqunxiax.adapter.TraditionFooterAdapter;
import all.com.jinyongqunxiax.decoration.EqualSpaceItemDecoration;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class ImagePickNetworkBaiduActivity extends AppCompatActivity {
    static int CAMERA_CROP_RESULT = 100;
    Options     options;
    SlimAdapter adapter;
    int         column = 3;
    boolean supportEdit = false; /// 是否支持编辑图片

//    public static Bitmap scaleImage(Bitmap originImage, float maxImageSize,
//                                    boolean filter) {
//        float ratio = Math.min(
//            maxImageSize / originImage.getWidth(),
//            maxImageSize / originImage.getHeight());
//        int width  = Math.round(ratio * originImage.getWidth());
//        int height = Math.round(ratio * originImage.getHeight());
//
//        return Bitmap.createScaledBitmap(originImage, width,
//            height, filter);
//    }
    UltimateRefreshView refreshView;
    SearchView          searchView;
    String searchURL = "http://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&ie=utf-8&st=-1&z=&ic=0&hd=&latest=&copyright=&s=&se=&tab=&width=&height=&face=0&istype=2&gsm=3c&1548149787800=";
    String query;
    int    pageIndex = 0;
    int    pageSize  = 60;
    List<ViewModel> viewModels = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_pick_network_baidu_activity);
        setTitle("替换");
        options = new Options(getIntent());

        RecyclerView recyclerView = findViewById(R.id.image_search_baidu_list_listView);


        // 设置布局管理器
        recyclerView.setLayoutManager(new GridLayoutManager(this, column, RecyclerView.VERTICAL, false));
        // 设置Item添加和移除的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        // 设置Item之间间隔样式
        recyclerView.addItemDecoration(new EqualSpaceItemDecoration(this, column, 10, 10));

        adapter = SlimAdapter.create().register(R.layout.image_pick_network_baidu_list_image_item, new SlimInjector<ViewModel>() {
                    @Override
                    public void onInject(@NonNull ViewModel viewModel, @NonNull IViewInjector injector) {
                        injector.text(R.id.image_search_baidu_list_image_title, viewModel.name);

                        ImageView imageView = (ImageView) injector.findViewById(R.id.image_search_baidu_list_image_view);
                        Glide.with(ImagePickNetworkBaiduActivity.this).load(viewModel.url).into(imageView);

                        injector.clicked(R.id.image_search_baidu_list_image_view, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                selectImage(viewModel);
                            }
                        });
                    }
                }
        ).attachTo(recyclerView);

        refreshView = findViewById(R.id.refreshView);
        refreshView.setBaseHeaderAdapter();
        refreshView.setBaseFooterAdapter(new TraditionFooterAdapter(this));
        refreshView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
            @Override
            public void onFooterRefresh(UltimateRefreshView view) {
                loadMoreData(view);
            }
        });
    }

    void selectImage(ViewModel viewModel) {
        Glide.with(ImagePickNetworkBaiduActivity.this).asBitmap().load(viewModel.url)
             .into(new SimpleTarget<Bitmap>() {
                       @Override
                       public void onResourceReady(
                               @NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                           processImage(resource);
                       }
                   }
             );
    }

    void processImage(Bitmap resource) {
        String           dir  = Environment.getExternalStorageDirectory().getPath();
        String           name = "temp.png";
        String           path = FilenameUtils.concat(dir, name);
        FileOutputStream out  = null;

        try {
            if (supportEdit) {
                out = new FileOutputStream(path);
                resource.compress(Bitmap.CompressFormat.PNG, 80, out);
                out.close();
                out = null;
                Uri uri = FileProvider.getUriForFile(this,
                        getApplicationContext().getPackageName() + ".provider",
                        new File(path));
                Uri target = FileProvider.getUriForFile(this,
                        getApplicationContext().getPackageName() + ".provider",
                        new File(path + "-new.png"));
                UCrop.of(uri, target)
                     .withAspectRatio(options.width, options.height)
                     .withMaxResultSize(options.width * 2, options.height * 2)
                     .start(this);


                // 只能裁剪一次
                //  CropImage.activity(uri).start(this);
            } else {
                Bitmap bitmap = ImageUitls.scaleImage(resource, options.width, options.height);
                setImageAsResult(bitmap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    void setImageAsResult(Bitmap bitmap) {
        Intent result = new Intent();
        Bundle extras = new Bundle();
        extras.putParcelable("data", bitmap);
        result.putExtras(extras);
        setResult(RESULT_OK, result);
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.filter_menu, menu);

        // SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        MenuItem item = menu.findItem(R.id.filter_search_view_item);
        searchView = (SearchView) item.getActionView();
        //searchView.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
        //searchView.setIconifiedByDefault(true);
        searchView.setQueryHint("在这里搜索, 图片大小:" + options.width + "x" + options.height);

        item.expandActionView();
        ImageView iconView = searchView.findViewById(androidx.appcompat.R.id.search_mag_icon);
        if (iconView != null) {
            ViewGroup parent = (ViewGroup) iconView.getParent();
            parent.removeView(iconView);
        }

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                loadNewData(query);
                searchView.clearFocus();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.searchActionBarItem:
                Logger.i("");
                return true;

            default:
                return true;
        }
    }

    void loadNewData(String query) {
        this.query = query;
        pageIndex = 0;
        viewModels.clear();
        search(query);
    }

    void loadMoreData(UltimateRefreshView refreshView) {
        pageIndex += 1;
        search(query);
    }

    void search(String query) {
        AndroidNetworking.setParserFactory(new JacksonParserFactory());
        AndroidNetworking.get(searchURL)
                         .addQueryParameter("word", query)
                         .addQueryParameter("queryWord", query)
                         .addQueryParameter("pn", "" + pageIndex * pageSize)
                         .addQueryParameter("rn", "" + pageSize).build().getAsJSONObject(new JSONObjectRequestListener() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray data = (JSONArray) response.get("data");
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject imageObject = (JSONObject) data.get(i);
                        /**
                         * hasLarge	Integer	0
                         * middleURL	String	http://img4.imgtn.bdimg.com/it/u=3606160828,1929488098&fm=26&gp=0.jpg
                         * width	    Integer	800
                         * height	Integer	600
                         * type	    String	jpeg
                         * is_gif	Integer	0
                         */
                        int    hasLarge = JSONUtility.getInt(imageObject, "hasLarge", 0);
                        String urlKey   = hasLarge == 0 ? "middleURL" : "largeURL";
                        String url      = JSONUtility.getString(imageObject, urlKey, "");
                        int    isGif    = JSONUtility.getInt(imageObject, "is_gif", 0);

                        int width  = JSONUtility.getInt(imageObject, "width", 0);
                        int height = JSONUtility.getInt(imageObject, "height", 0);

                        if (isGif != 0 || TextUtils.isEmpty(url)) {
                            continue;
                        }

                        ViewModel viewModel = new ViewModel();
                        viewModel.url = url;
                        viewModel.name = width + "x" + height;

                        viewModels.add(viewModel);
                    }

                    adapter.updateData(viewModels);

                    if (pageIndex != 0) {
                        refreshView.onFooterRefreshComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(ANError error) {
                Logger.e(error.toString());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
//        if (requestCode == UCrop.REQUEST_CROP) {
//            if (data == null) {
//                return;
//            }
//
//            final Uri resultUri = UCrop.getOutput(data);
//            Bitmap    bitmap    = BitmapFactory.decodeFile(resultUri.getPath());
//        }

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (result == null) {
                return;
            }
            Uri    resultUri = result.getUri();
            Bitmap bitmap    = BitmapFactory.decodeFile(resultUri.getPath());
            setImageAsResult(bitmap);
        }
    }

    public static class Options {
        int width;
        int height;
        Options(Intent intent) {
            this.width = intent.getIntExtra("width", 0);
            this.height = intent.getIntExtra("height", 0);
        }

        static Intent intent(Context context, int width, int height) {
            Intent intent = new Intent(context, ImagePickNetworkBaiduActivity.class);
            intent.putExtra("width", width);
            intent.putExtra("height", height);

            return intent;
        }
    }

    static class ViewModel {
        String url;
        String name;
    }
}
